<?php
// set up our include_path so we can easily include the magpie rss parser library later
ini_set('include_path', ini_get('include_path').':'.APPPATH.'libraries/magpie_rss/');

class BlockInstance {
	public static function get_template_path($name)
	{
		$path = APPPATH."libraries/blocks/{$name}.php";
		return $path;
	}
	
	public static function load_block_file($path, $name)
	{
		if (!file_exists($path))
			show_error("BricaBox couldn't load the block file for {$name}");
		else
			require_once $path;
		
		$CI =& get_instance();
		$CI->load->helper('inflector');
		
		// instantiate an instance of the block instance class and return it;
		// class name can be optionally suffixed with Block, to avoid naming conflicts
		$klass_name = ucfirst(camelize($name));
		if (class_exists($klass_name))
			$klass = new $klass_name;
		elseif (class_exists($klass_name.'Block'))
		{
			$klass_name = $klass_name.'Block';
			$klass 		= new $klass_name;
		}
		else
			show_error("BricaBox couldn't instantiate a BlockInstance for {$klass_name} or {$klass_name}Block");
		return $klass;
	}
	
	public static function title_for_block($block_data)
	{
		if (strlen($block_data['data']->title))
			return $block_data['data']->title;
		else
			return $block_data['parent']->title; // default
	}
	
	public function handle_proxy($bricabox_id, $params, $parent_name, $tpl_path, $instance, $parent)
	{
	}
	
	public function get_setting(&$instance, $name, $content_id = false, $default = false)
	{
		// keyed off of only content_id ?
		if ($content_id !== false)
			$query = $this->CI->db->query('select value from meta_settings where name = ? and content_id = ? limit 1', array($name, $content_id));
		else
			$query = $this->CI->db->query('select value from meta_settings where block_instance_id = ? and name = ? limit 1', array($instance->id, $name));
		
		if ($query->num_rows() == 1)
			return $query->first_row()->value;
		else
			return $default;
	}
	
	// acts similarly to Rails' find_or_create_by*
	public function save_setting(&$instance, $name, $value, $content_id = false)
	{
		if ($this->get_setting($instance, $name, $content_id) === false)
			$query = $this->CI->db->query('insert into meta_settings (block_instance_id,name,value,content_id)
				values(?,?,?,?)', array($instance->id, $name, $value, $content_id));
		else
			if ($content_id === false)
				$query = $this->CI->db->query('update meta_settings
					set value = ?,content_id = ?
					where name = ? and block_instance_id = ?',
					array($value, $content_id, $name, $instance->id));
			else
				$query = $this->CI->db->query('update meta_settings
					set value = ?
					where name = ? and content_id = ?',
					array($value, $name, $content_id));
	}
}
?>